10. Foreign Key Constraint Setup

Setting up the Foreign Key Constraint

ND004 C01 L07 10 Setting Up The Foreign Key Constraint

Takeaways

  • db.relationship does not set up foreign key constraints for you. We need to add a column, some_parent_id , on the child model that has a foreign key constraint
  • Whereas we set db.relationship on the parent model, we set the foreign key constraint on the child model.
  • A foreign key constraint prefers referential integrity from one table to another, by ensuring that the foreign key column always maps a primary key in the foreign table.

db.ForeignKey question

ND004 C01 L07 10.1 Setting Up The Foreign Key Constraint

db.ForeignKey

  • Option in db.column to specify a foreign key constraint, referring to the primary key of the other table / model
  • Gets defined on the Child model

True/False: db.relationship sets up foreign keys

SOLUTION: False

Model Q

QUIZ QUESTION: :

On which model do we define each of the following?

ANSWER CHOICES:



SQLAlchemy concept

Model

Child Model

Parent Model

SOLUTION:

SQLAlchemy concept

Model

Child Model

Parent Model

db.ForeignKey

db.ForeignKey is passed into…

SOLUTION: `db.Column`

Choose the correct option to fill in the <BLANK> to set up the foreign key constraint between these two models:

class School(db.Model):
  __tablename__ = 'schools'
  id = db.Column(db.Integer, primary_key=True)
  # ...

class Teacher(db.Model):
  __tablename__ = 'teachers'
  id = db.Column(db.Integer, primary_key=True)
  name = #...
  school_id = db.Column(db.Integer, <BLANK>)
SOLUTION: `db.ForeignKey('schools.id')`

Now let's apply what we learned to an example

ND004 C01 L07 10.2 Setting Up The Foreign Key Constraint

Write out the Driver and Vehicle models

Workspace

This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity , so you may be able to download them there.

Workspace Information:

  • Default file path:
  • Workspace type: generic
  • Opened files (when workspace is loaded): n/a

Did you get it right?

Watch the next video to find out!

ND004 C01 L07 10.3 Setting Up The Foreign Key Constraint